import axios from 'axios'
import {ElLoading, ElMessage} from 'element-plus'

const instance = axios.create({
    headers: {
        'Content-Type': 'application/json',
    },
})

//加载动画
let loading = null

instance.interceptors.request.use(
    function (config) {
        const baseUrl = import.meta.env.MODE == 'development' ? 'http://map.test/api' : '/api'
        config.baseURL = baseUrl

        //携带令牌
        const token = window.localStorage.getItem('token')
        if (token) config.headers.Authorization = `Bearer ${token}`
        //加载动画
        loading = ElLoading.service({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(255, 255, 255, 0)',
        })
        return config
    },
    function (error) {
        return Promise.reject(error)
    }
)

instance.interceptors.response.use(
    function (response) {
        loading.close()
        const {data} = response
        if (data.message) {
            ElMessage.success({
                message: data.message,
                type: 'success',
            })
        }

        return data
    },
    function (error) {
        loading.close()
        const {status, data} = error.response

        switch (status) {
            case 405:
                ElMessage.error({
                    message: data.message,
                    type: 'error',
                })
                break;
            case 422:
                //表单验证失败
                break
            case 401:
                console.error("401")
                // 清空缓存
                localStorage.clear()
                window.location.href = "#/admin"
                break
        }

        return Promise.reject(error)
    }
)

export default instance